<?php
/**
 * CK 开发框架
 * User: Clake
 * Date: 15/6/18
 * Time: 00:57
 */

namespace CK\Database;


class MultiDeleteTable {
//build sql script
    public $sql_str;
    /**
     * dba class
     * @var DBA
     */
    private $dba;

    private $tables;

    private $table_name;

    private $params;

    private $where_str;

    private $join;

    function __construct($data_source,$table){
        $this->dba = $data_source;
        $this->table_name = $table;
        $this->clear();
    }

    function clear() {
        $this->sql_str = "";
        $this->params = array();
        $this->where_str = "";
        $this->tables = array();
        $this->join = "";
    }

    function del_tables($tables) {
        if (is_array($tables)) {
            $this->tables = $tables;
        }
    }

    function join($table_t,$column_t,$table_f,$column_f,$join="INNER"){
        $table_f = $this->dba->format($table_f);
        $table_t = $this->dba->format($table_t);
        $column_t = $this->dba->format($column_t);
        $column_f = $this->dba->format($column_f);
        $join = strtoupper($join);

        $this->join .= " $join JOIN $table_t ON $table_t.$column_t=$table_f.$column_f\n";
    }

    function where($where_field,$table=null){
        $table = $table ? $table : $this->table_name;
        $where_str = "";
        foreach ($where_field as $column => $value) {
            $where_str .= $this->dba->format_where($column, $value,$table);
        }
        $this->where_str = $where_str;
    }

    function execute() {
        $del_tab_str = "";
        foreach ($this->tables as $tab) {
            $tab = $this->dba->format($tab);
            $del_tab_str .= $tab.",";
        }
        $del_tab_str  = substr($del_tab_str, 0, strlen($del_tab_str)-1);

        $main_tab = $this->dba->format($this->table_name);

        $sql = "DELETE $del_tab_str FROM $main_tab
		$this->join WHERE 1=1 $this->where_str";

        foreach ($this->params as $key => $value) {
            $sql = str_replace($key, $value, $sql);
        }

        $this->sql_str = $sql;
        $this->dba->query($sql);

        return $this->dba->h_query?true:false;
    }
}